from pyglet.gl import *
from vec2d import Vec2d

class SeaFloor:
    """The bottom of the ocean"""

    def __init__(self, game):
        self.heights = [0] * game.width
        self.max_height = 0
        self.max_right = game.width - 1

    def collision_point(self, sprite, x_offset=0, y_offset=0, hardness=1.0):
        """Return a vector at the point of collision with the sea floor or None
        if the sprite does not collide

        If hardness is < 1.0 the sprite is allowed to penetrate the bottom
        somewhat.
        """
        sprite_bottom = int(
            sprite.y + y_offset + sprite.image.anchor_y - sprite.height 
            + sprite.height * (1.0 - hardness))
        sprite_left = int(sprite.x + x_offset - sprite.image.anchor_x)
        sprite_left += int(sprite.width  * (1.0 - hardness) * 0.5)
        sprite_right = int(sprite.x + x_offset - sprite.image.anchor_x + sprite.width)
        sprite_right -= int(sprite.width * (1.0 - hardness) * 0.5)
        if sprite_bottom < self.max_height and (
            sprite_right >= 0 or sprite_left <= self.max_right):
            collide_y = -1
            collide_x = -1
            heights = self.heights
            for x in range(max(sprite_left, 0), min(sprite_right, self.max_right)):
                h = heights[x]
                if sprite_bottom <= h and h > collide_y:
                    collide_x = x
                    collide_y = h
            if collide_x > -1:
                return Vec2d(collide_x, collide_y)

    def pile_sprite(self, sprite):
        """Piles the sprite onto the sea floor, raising it"""
        sprite_top = sprite.y + sprite.image.anchor_y
        sprite_left = int(sprite.x - sprite.image.anchor_x)
        sprite_right = int(sprite.x + sprite.width - sprite.image.anchor_x)
        if sprite_right >= 0 or sprite_left <= self.max_right:
            heights = self.heights
            for x in range(max(sprite_left, 0), min(sprite_right, self.max_right)):
                if sprite_top > heights[x]:
                    heights[x] = sprite_top
                    if sprite_top > self.max_height:
                        self.max_height = sprite_top

    def draw(self):
        glColor3f(1.0, 1.0, 0.0)
        glBegin(GL_POINTS)
        for x, y in enumerate(self.heights):
            glVertex2f(x, y)
        glEnd();
